<?php
/**
 * Created by jinqiang on 2024/6/24 17:35.
 * Copyright (c) 2024, Your Company. All rights reserved.
 */


namespace App\Http\Controllers\Tool;


use App\Http\Controllers\Controller;
use App\Http\Models\Mysql\SsyJyProductListTable;
use App\Http\Models\Mysql\SsyStyleAttachTable;
use App\Http\Repository\CommonRepository;
use App\Http\Services\Banshi\DesignService;
use App\Http\Services\Om\ExportService;
use App\Http\Services\Op\LendService;
use App\Http\Services\Tool\fileService;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use PhpOffice\PhpSpreadsheet\IOFactory;

class FileController extends Controller
{
    //导出
    public function export(Request $request, fileService $fileService)
    {
        $this->validate($request, [
            'path' => 'required',
            'name' => 'required',
            'type' => 'required|in:url,file,pdf,excel'
        ]);
        $param = $request->all();
        switch ($param['type']){
            case 'url':
                CommonRepository::downFile($param['path'], $param['name']);
                break;
            case 'file':
                $file = storage_path("{$param['path']}/").$param['name'];
                CommonRepository::downFile($file, $param['name'], 'file');
                break;
            case 'pdf':
                if($param['name'] == '返修对账单'){
                    list($filename, $title, $html) = $fileService->repairPdf((Int)$param['path']);
                    CommonRepository::downPdf($filename, $title, $html);
                }
                if($param['name'] == '对账单'){
                    list($filename, $title, $html) = $fileService->reconciliationPdf((Int)$param['path']);
                    CommonRepository::downPdf($filename, $title, $html);
                }
                break;
            case 'excel':
                if($param['name'] == '返修对账单'){
                    $fileService->repairExcel((Int)$param['path']);
                }
                if($param['name'] == '绣花对账单(暂估)'){
                    $fileService->xhzgExcel((Int)$param['path']);
                }
                if($param['name'] == '对账单'){
                    $fileService->reconciliationExcel((Int)$param['path']);
                }
                if($param['name'] == '大货BOM'){
                    $fileService->bomExcel((Int)$param['path'], 1);
                }
                if($param['name'] == '物料清单'){
                    $fileService->bomExcel((Int)$param['path'], 0);
                }
                if($param['name'] == '售罄率'){
                    $fileService->salesRateExcel($param['path']);
                }
                break;
        }
        return success('操作成功');
    }

    //上传
    public function import(Request $request)
    {
        $this->validate($request, [
            'type' => 'required',
            'disk' => 'required|in:file,excel,image,material,style'
        ]);
        $param = $request->all();
        $file = $_FILES['file'] ?? [];
        $tmpFile = $file['tmp_name'] ?? "";
        $user = auth()->guard("api")->user();
        $fileSize = isset($file['size']) ? $file['size']/1024/1024 : 0;
        //超过20M 不允许
        if(!empty($fileSize) && $fileSize>=20){
            return error("文件大小超过限制(20M)", $fileSize);
        }
        switch ($param['type']){
            case "design_attach"://设计档案 附件
                $fileNameArr = explode(".", $file['name']);
                $fileName = date('YmdHis')."_".md5($fileNameArr[0]).".".$fileNameArr[1];
                $fileRes = CommonRepository::uploadCDN($tmpFile, $param['disk'], $fileName);
                if($fileRes['code'] != 0){
                    return error("文件上传失败", $fileRes);
                }
                $data = [
                    'type_no' => $param['type_no'],
                    'name' => $file['name'],
                    'url' => $fileRes['file'],
                    'createtime' => date('Y-m-d H:i:s')
                ];
                return (new SsyStyleAttachTable())->createData($data);
            case "sealed_sample"://工艺单 相关资料
                $fileNameArr = explode(".", $file['name']);
                $fileName = date('YmdHis')."_".md5($fileNameArr[0]).".".$fileNameArr[1];
                $fileRes = CommonRepository::uploadCDN($tmpFile, $param['disk'], $fileName);
                if($fileRes['code'] != 0){
                    return error("文件上传失败", $fileRes);
                }
                $param = [
                    'title' => $file['name'],
                    'group_id' => (Int)$param['tab'],
                    'type_id' => (Int)$param['radioTab'],
                    'url' => $fileRes['file'],
                    'type_no' => $param['type_no']
                ];
                $res = (new DesignService())->createDetailFile($param);
                return $res['code'] === 0 ? success("上传成功", $fileRes['file']) : error($res['msg'], $res);
            case "lend_ipurchase"://借赠还，借出转内购，付款截图
            case "soa_pricing_check"://核价单审核，实付核价截图说明
            case "soa_cy_repairM"://返修退款对账单，付款凭证
            case "soa_xh_manage"://绣花对账单，付款凭证
            case "soa_cy_manage"://成衣对账单，付款凭证
            case "produce_factory"://加工厂管理
            case "soa_xh_contract"://绣花合同
            case "soa_cy_contract"://成衣合同
            case "design_rule"://尺寸表图片上传
            case "design_gy"://工艺单图片上传
            case "bs_materiel"://物料档案
                $fileNameArr = explode(".", $file['name']);
                $fileName = $user->id."_".md5(time().$fileNameArr[0]).".".$fileNameArr[1];
                $fileRes = CommonRepository::uploadCDN($tmpFile, $param['disk'], $fileName);
                if($fileRes['code'] != 0){
                    return error("文件上传失败", $fileRes);
                }
                return success("上传成功", $fileRes['file']);
            case "design_style"://设计档案--款式图片
                $fileNameArr = explode(".", $file['name']);
                $fileName = $param['name']."_".date('His').".".$fileNameArr[1];
                //CommonRepository::delectCDN($param['disk']."/".$fileName, $param['disk']);
                $fileRes = CommonRepository::uploadCDN($tmpFile, $param['disk'], $fileName);
                if($fileRes['code'] != 0){
                    return error("文件上传失败", $fileRes);
                }
                return success("上传成功", $fileRes['file']);
                break;
            case "design_gy_process"://工艺单指示图
                $imgContent = $param['img'];
                $imgType = preg_match('/^(data:\s*image\/(\w+);base64,)/', $imgContent, $dd) ? $dd[2] : "png";
                $filename = md5($imgContent).".{$imgType}";
                $imgContent = base64_decode(str_replace($dd[1], '', $imgContent));
                $fileRes = CommonRepository::uploadCDN($tmpFile, $param['disk'], $filename, $imgContent);
                if($fileRes['code'] != 0){
                    return error("文件上传失败", $fileRes);
                }
                $img_64 = "data:image/{$imgType};base64,".base64_encode(file_get_contents($fileRes['file']));
                return success("上传成功", ['img' => $fileRes['file'], 'img_64' => $img_64]);
            case "produce_baoci"://报次表格批量导入
            case "op_lend"://借赠申请
                $subject = array_column(config('scm.subject'), 'brand_code_jy', 'is_subject');
                $spreadsheet = IOFactory::load($tmpFile);
                $sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
                array_shift($sheetData);
                $skuCodes = array_column($sheetData, 'A');
                $list = (new SsyJyProductListTable())->whereIn('product_code', $skuCodes)->where('brand_code', $subject[$user->is_subject])
                    ->get(['img', 'product_name', 'product_code'])->toArray();
                $listMap = array_column($list, null, 'product_code');
                $data = [];
                foreach ($sheetData as $item){
                    if(empty($item['A'])){
                        continue;
                    }
                    if(!isset($listMap[$item['A']])){
                        return error("导入失败：{$item['A']}, 当前主体, 商品信息不存在");
                    }
                    $data[] = array_merge(['num' => $item['B'], 'price' => $item['C'] ?? ""], $listMap[$item['A']]);
                }
                return success("上传成功", $data);
            case "op_lendsale"://借转销售
                $spreadsheet = IOFactory::load($tmpFile);
                $sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
                array_shift($sheetData);
                $orders = [];
                $lendMap = [];
                foreach($sheetData as $order){
                    if(empty($order['A']) || empty($order['B'])){
                        unset($order);
                        continue;
                    }
                    $lendDetail = $lendMap[$order['A']] ?? [];
                    if(empty($lendDetail)){
                        $lendDetail = array_column((new LendService())->lendList($order['A']), null, 'sku_code');
                        $lendMap[$order['A']] = $lendDetail;
                    }
                    $orders[] = [
                        'A' => $order['A'],
                        'B' => $order['B'],
                        'C' => (Int)$order['C'],
                        'D' => (Double)$order['D'],
                        'type_name' => $lendDetail[$order['B']]['type_name'],
                        'img' => $lendDetail[$order['B']]['img'],
                        'num' => $lendDetail[$order['B']]['num'],//计划借出
                        'actually_num' => $lendDetail[$order['B']]['actually_num'],//实际借出数
                        'actually_return_num' => $lendDetail[$order['B']]['actually_return_num'],//实际归还数
                        'ipurchase_num' => $lendDetail[$order['B']]['ipurchase_num'],//已转内购数
                        'give_num' => $lendDetail[$order['B']]['give_num'],//已转赠送数
                        'sale_num' => $lendDetail[$order['B']]['sale_num'],//已转销售数
                    ];
                }
                if(count($lendMap) > 1){
                    return error("上传失败，出现多个不同的借出单号（涉及金蝶销售出库单据来源）");
                }
                return success("上传成功", $orders);
            case "om_inventory"://库存分配--到货日期
                $spreadsheet = IOFactory::load($tmpFile);
                $sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
                array_shift($sheetData);
                foreach ($sheetData as $item){
                    if(empty($item['A'])){
                        continue;
                    }
                    (new SsyJyProductListTable())->updateDataWhere(['type_no' => $item['A']], [
                        'arrivaldate' => trim($item['B']),
                        'arrivaldate_title' => trim($item['C'])
                    ]);
                }
                return success("设置成功");
            case "om_export"://运营订单
                $spreadsheet = IOFactory::load($tmpFile);
                $sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
                array_shift($sheetData);
                $typeNos = array_unique(array_column($sheetData, 'A'));
                $sheetMap = array_column($sheetData, null, 'B');
                $res = (new ExportService())->searchStyle(['numbers' => $typeNos, 'page' => 1, 'limit' => count($typeNos)]);
                $data = [];
                foreach ($res['data'] as $item){
                    $flag = false;
                    foreach ($item['style_size'] as &$sizeObj){
                        $sku = $item['number'].$item['style_colour']['colour_number'].$sizeObj['size_number'];
                        if(isset($sheetMap[$sku])){
                            $flag = true;
                            $sizeObj['count'] = $sheetMap[$sku]['C'] ?? "";
                        }
                    }
                    unset($sizeObj);
                    if($flag){
                       $data[] = $item;
                    }
                }
                unset($item);
                if(empty($data)){
                    return error("上传失败：未解析到上传数据,请核对表格数据是否规范");
                }
                return success("上传成功", $data);
            case "oms_sales"://渠道销售--订单明细
                $path = storage_path("cache/sales/");
                $ctime = date('YmdHis');
                $fileName = "销售单_".$user->name."_{$ctime}_".$file['name'];
                // 将临时文件移动到服务器目标位置
                if (move_uploaded_file($file['tmp_name'], $path.$fileName)) {
                    $data = [
                        'create_user' => $user->name,
                        'create_time' => date('Y-m-d H:i:s', strtotime($ctime)),
                        'name' => preg_replace("/^销售单_(.*?)_(\d{14})_/is", "", $fileName),
                        'full_name' => $fileName,
                        'status' => 0,
                        'process' => 0
                    ];
                    $cache = ['file' => $fileName, 'process' => 0, 'param' => ['source' => $param['source']]];
                    Cache::put("SALES_EXCEL_IMPORT", $cache, Carbon::now()->addSeconds(60));
                    $cmd = 'php '.base_path().'/artisan command:importData --key=SALES_EXCEL_IMPORT >/dev/null 2>&1 &';
                    ppopen($cmd);
                    return success("保存文件成功", ['data' => $data, 'cache' => $cache]);
                } else {
                    return error("保存文件失败，请检查服务器目录权限");
                }
            default:
                return error("业务类型不能为空：{$param['type']}");
        }
    }
}
